package com.example.customizedgroupmessage;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Menu;
import android.view.View;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.widget.*;

import java.util.Date;
import java.text.SimpleDateFormat;

public class MailTemplate extends Activity {

	public static final int REQUEST_CODE_MAILCUSTOMWORD=2004;
	public static final int REQUEST_CODE_TEMPLATEBOXACTIVITY=2005;
	public static final int REQUEST_CODE_MAILTEMPLATECALL=2006;
	public static final int REQUEST_CODE_MAILSEND=2007;
	
	// 템플릿
	public static Template mailTemplate;
	DBHelper mHelper;
	SQLiteDatabase db;
	TextView textTargetUri;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mail_template);
		
		
		
		// sms Template db 생성
		mHelper = new DBHelper(this);
		
		// 템플릿 생성
		mailTemplate = new Template();
		
		final EditText ed2 =(EditText)findViewById(R.id.editMailTitle);
		// 불러오기 버튼
		Button btnCall = (Button)findViewById(R.id.btnMailCall);
		btnCall.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				// 인텐트 객체를 생성
				Intent intent = new Intent(MailTemplate.this, MailTemplateCall.class);
				// 결과값을 받기 위한 Sub Activity 호출
				startActivityForResult(intent, REQUEST_CODE_MAILTEMPLATECALL);
			}
		});
	
		

		
		
		// 템플릿 저장 버튼
		Button btnTemplatSave = (Button)findViewById(R.id.btnMailTemplateSave);
		btnTemplatSave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				final EditText ed1 =(EditText)findViewById(R.id.editMailText);
				Builder builder = new AlertDialog.Builder(MailTemplate.this);
				
				// 텍스트상자에 내용이 없으면
				if(ed1.getText().toString().length()==0){
					builder.setMessage("입력된 내용이 없습니다.");
					builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
						}
					});
				}
				
				// 텍스트상자에 내용이 있으면 저장할지 묻는다.
				else{
					builder.setMessage("저장 하시겠습니까?");
					builder.setPositiveButton("취소", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {    
							dialog.cancel();
						}
					});
					builder.setNegativeButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							db = mHelper.getWritableDatabase();
							String _id;
							String msg;
							String msgtitle;
							Date date = new Date();
							SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd (hh:mm:ss)");
							
							_id = df.format(date).toString();
							msg = ed1.getText().toString();
							msgtitle= ed2.getText().toString();
							db.execSQL("INSERT INTO mailtemplate VALUES ('"+_id+"', '"+msgtitle+"', '"+msg+"');");
							mHelper.close();
							
							Toast.makeText(MailTemplate.this, "저장 되었습니다.", Toast.LENGTH_SHORT).show();
						}
					});
				}
				builder.show();
			}
		});
		
		
		
		// 이름
		Button btnName = (Button)findViewById(R.id.btnMailName);
		btnName.setOnClickListener(new Button.OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editMailText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##name/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.name_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		
				/*String string ="/##name/#";
				int color =Color.GRAY;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder);*/
			}
		});
		
		// 직위
		Button btnStatus = (Button)findViewById(R.id.btnMailStatus);
		btnStatus.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editMailText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##status/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.status_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
			/*	EditText ed1 =(EditText)findViewById(R.id.editText);
				String string ="/##status/#";
				int color =Color.BLUE;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder); 	*/	
				
			}
		});
		
		// 소속
		Button btnOrganization = (Button)findViewById(R.id.btnMailOrganization);
		btnOrganization.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editMailText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##org/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.org_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
				
				/*EditText ed1 =(EditText)findViewById(R.id.editText);
				String string ="/##org/#";
				int color =Color.LTGRAY;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder); 	*/
				
			}
		});
		
		// 지정
		Button btnCustom = (Button)findViewById(R.id.btnMailCustom);
		btnCustom.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				//Intent intent = new Intent(getBaseContext(), TemplateBoxActivity.class);
				//startActivityForResult(intent, REQUEST_CODE_SMSGROUPLISTVIEW);
				EditText ed1 =(EditText)findViewById(R.id.editMailText);
				int st_index = ed1.getSelectionStart();
				ed1.getText().insert(st_index, "/##custom/#");
				int et_index = ed1.getSelectionEnd();
				Spannable span = ed1.getText();
				Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.custom_ed);
				span.setSpan(new ImageSpan(bm), st_index, et_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				
				/*EditText ed1 =(EditText)findViewById(R.id.editText);
				String string ="/##custom/#";
				int color =Color.GREEN;
				SpannableStringBuilder builder =new SpannableStringBuilder(string);
				builder.setSpan(new ForegroundColorSpan(color), 0, 11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				ed1.append(builder); 	*/
			}
		});
		
		//파일 첨부
		Button btnFile = (Button)findViewById(R.id.btnFile);
		textTargetUri = (TextView)findViewById(R.id.file);
		
		btnFile.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				String action = Intent.ACTION_PICK;
				Uri uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
				Intent intent = new Intent(action, uri);
        		
				startActivityForResult(intent, REQUEST_CODE_MAILSEND); 			 
			    
			}
		});
		
		
		// 다음 버튼
		Button btnSMSWirteNext = (Button)findViewById(R.id.btnMailWirteNext);
		btnSMSWirteNext.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				EditText ed1 =(EditText)findViewById(R.id.editMailText);
				Builder builder = new AlertDialog.Builder(MailTemplate.this);
				
				// 텍스트상자에 내용이 없으면
				if(ed1.getText().toString().length()==0){
					builder.setMessage("입력된 내용이 없습니다.");
					builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
						}
					});
				}
				//제목이 입력되어 있지 않으면
				else if(ed2.getText().toString().length()==0){
					builder.setMessage("제목이 입력되지 않았습니다.");
					builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
						}
					});
				}
				// 텍스트상자에 내용이 있으면 
				else{
					mailTemplate.setTitle(ed2.getText().toString());
					mailTemplate.setOriginalMsg(ed1.getText().toString());
					mailTemplate.analyzeMsg(); // 메시지 분석(분할)
					
					for(int i=0; i<mailTemplate.getAnalyzedMsg().length; i++){
						// custom 있는 경우
						if( mailTemplate.analyzedMsg[i].equals("#custom") ){
							Intent intent = new Intent(getBaseContext(), MailCustomWord.class);
							if(selectedImage!=null){
							intent.putExtra("uri", selectedImage.toString());
							}
							startActivityForResult(intent, REQUEST_CODE_MAILCUSTOMWORD);
						}
						// custom 없는 경우
						else {
							Intent intent = new Intent(getBaseContext(), MailSendActivity.class);
							if(selectedImage!=null){
								intent.putExtra("uri", selectedImage.toString());
							}
							
							startActivityForResult(intent, REQUEST_CODE_MAILSEND);
						}
					}
				}
				builder.show();
	
			}
		});
		
	
	}
	
	Uri selectedImage=null;
	
	// onActivityResult()는 결과를 받는 이벤트 핸들러로,
    // startActivityForResult()로 호출한 액티비티가 종료되었을 때 호출된다.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_MAILSEND) {        
        	if (resultCode == Activity.RESULT_OK) {           
        		selectedImage = data.getData();            // TODO Do something with the select image URI        
        		Intent intent01 = new Intent(MailTemplate.this, MailSendActivity.class);
                intent01.putExtra("uri", selectedImage.toString());
                textTargetUri.setText("Uri: " + selectedImage);
      
        	}
        }
        
        if(requestCode == REQUEST_CODE_MAILTEMPLATECALL) // Sub Activity 호출시 사용된 요청 코드
        {
            if(resultCode == RESULT_OK) // Sub Activity의 결과 코드
            {
                // 받아온 메시지를 액티비티에 표시한다.
            	EditText ed0 = (EditText)findViewById(R.id.editMailTitle);
            	EditText ed1 = (EditText)findViewById(R.id.editMailText);
            	
            	ed0.setText(data.getStringExtra("msgTitle"));
                ed1.setText(data.getStringExtra("originalMsg"));
                
                mailTemplate.setOriginalMsg(data.getStringExtra("originalMsg"));
                mailTemplate.analyzeMsg();
                ed1.setText("");
        		
        		for(int i =0; i < mailTemplate.analyzedMsg.length ; i++){
        			if(mailTemplate.analyzedMsg[i].equals("#name")){
        				Drawable d = getResources().getDrawable(R.drawable.name);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(mailTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else if(mailTemplate.analyzedMsg[i].equals("#status")){
        				Drawable d = getResources().getDrawable(R.drawable.status);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(mailTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else if(mailTemplate.analyzedMsg[i].equals("#org")){
        				Drawable d = getResources().getDrawable(R.drawable.org);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(mailTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else if(mailTemplate.analyzedMsg[i].equals("#custom")){
        				Drawable d = getResources().getDrawable(R.drawable.custom);
        				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        				SpannableString sText = new SpannableString(mailTemplate.analyzedMsg[i]);
        				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        				ed1.append(sText);
        			}
        			else{
        				ed1.append(mailTemplate.analyzedMsg[i]);
        			}
        		}
           
            }
        }
    }


}

